#include<stdio.h>
#include<Windows.h>
#include<stdlib.h>
#include<time.h>
#include<conio.h>

#define ROW 22
#define COL 42

#define KONG 0
#define WALL 1
#define FOOD 2
#define HEAD 3
#define BODY 4

#define UP 72
#define DOWN 80
#define LEFT 75
#define RIGHT 77
#define SPACE 32
#define ESC 27


struct Snake{
	int length;
	int x;
	int y;
}snake;


struct Body{
	int x;
	int y;
}body[ROW*COL];

int face[ROW][COL];

void HideCursor();
void CursorJump(int x,int y);
void InitInterface();
void color(int c);
void ReadGrade();
void WriteGrade();
void InitSnake();
void RandFood();
void JudgeFunc(int x,int y);
void DrawSnake(int flag);
void MoveSnake(int x,int y);
void run(int x,int y);
void Game();

int max,grade;
int main(){
	max=0,grade=0;
	system("title 贪吃蛇");
	system("mode con cols=84 lines=23");
	HideCursor();
	ReadGrade();
	InitInterface();
	InitSnake();
	srand((unsigned int)time(NULL));
	RandFood();
	DrawSnake(1);
	Game();
	return 0;
}

void HideCursor(){
	CONSOLE_CURSOR_INFO curInfo;
	curInfo.dwSize=1;
	curInfo.bVisible=FALSE;
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorInfo(handle,&curInfo);
}

void CursorJump(int x,int y){
	COORD pos;
	pos.X=x;
	pos.Y=y;
	HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
	SetConsoleCursorPosition(handle,pos);
}

void InitInterface(){
	color(6);
	for(int i=0;i<ROW;i++){
		for(int j=0;j<COL;j++){
			if(j==0||j==COL-1){
				face[i][j]=WALL;
				CursorJump(2*j,i);
				printf("■");
			}
			else if(i==0||i==ROW-1){
				face[i][j]=WALL;
				CursorJump(2*j,i);
				printf("■");
			}
			else{
				face[i][j]=KONG;
			}
		}
	}
	color(7);
	CursorJump(0,ROW);
	printf("当前得分:%d",grade);
	CursorJump(COL,ROW);
	printf("历史最高得分:%d",max);
}

void color(int c){
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),c);
}

void ReadGrade(){
	FILE* pf=fopen("贪吃蛇最高得分记录.txt","r");
	if(pf==NULL){
		pf=fopen("贪吃蛇最高得分记录.txt","w");
		fwrite(&max,sizeof(int),1,pf);
	}
	fseek(pf,0,SEEK_SET);
	fread(&max,sizeof(int),1,pf);
	fclose(pf);
	pf=NULL;
}

void WriteGrade(){
	FILE* pf=fopen("贪吃蛇最高得分记录.txt","w");
	if(pf==NULL){
		printf("保存最高得分记录失败\n");
		exit(0);
	}
	fwrite(&grade,sizeof(int),1,pf);
	fclose(pf);
	pf=NULL;
}

void InitSnake(){
	snake.length=2;
	snake.x=COL /2;
	snake.y=ROW /2;
	body[0].x=COL /2-1;
	body[0].y=ROW /2;
	body[1].x=COL /2-2;
	body[1].y=ROW /2;
	face[snake.y][snake.x]=HEAD;
	face[body[0].y][body[0].x]=BODY;
	face[body[1].y][body[1].x]=BODY;
}






